import os
import re
import pandas as pd
from datetime import datetime
import plotly.express as px

# 目录配置
MONTH_EVAL_DIR = r"E:\工作临时文件\Evaluate_data\Month_data\month_workers_evaluate"
IMAGE_RESULT_DIR = r"E:\工作临时文件\Evaluate_data\image_result"


def extract_month_from_filename(filename: str):
    """
    从文件名提取 YYYY-MM 形式的月份
    e.g. '2024年08月员工绩效系数.xlsx' -> '2024-08'
    """
    m = re.search(r"(\d{4})年(\d{2})月", filename)
    if m:
        return f"{m.group(1)}-{m.group(2)}"
    return None


def load_all_monthly_data():
    """
    读取目录下所有 'xx年xx月员工绩效系数.xlsx' 文件，返回合并DataFrame
    """
    all_rows = []

    for fname in os.listdir(MONTH_EVAL_DIR):
        if fname.endswith("员工绩效系数.xlsx"):
            month_label = extract_month_from_filename(fname)
            if not month_label:
                continue

            fpath = os.path.join(MONTH_EVAL_DIR, fname)
            try:
                df = pd.read_excel(fpath)
                # 确保有 '员工' & '月度绩效得分'
                if "员工" in df.columns and "月度绩效得分" in df.columns:
                    for _, row in df.iterrows():
                        all_rows.append({
                            "月份": month_label,
                            "员工": str(row["员工"]).strip(),
                            "绩效系数": float(row["月度绩效得分"])
                        })
            except Exception as e:
                print(f"⚠️ 无法读取文件 {fpath}: {e}")

    return pd.DataFrame(all_rows)


def plot_employee_bar(df_all, employee):
    """
    绘制单个员工近12个月绩效系数柱状图
    """
    df_emp = df_all[df_all["员工"] == employee].copy()

    # 按月份排序
    df_emp["月份排序"] = pd.to_datetime(df_emp["月份"] + "-01")
    df_emp.sort_values("月份排序", inplace=True)

    # 只取最近12个月
    df_emp = df_emp.tail(12)

    fig = px.bar(df_emp,
                 x="月份",
                 y="绩效系数",
                 text="绩效系数",
                 title=f"{employee} 最近12个月绩效系数",
                 labels={"绩效系数": "绩效系数值", "月份": "月份"})
    fig.update_traces(texttemplate='%{text:.2f}', textposition='outside')
    fig.update_layout(
        xaxis=dict(categoryorder='category ascending'),
        yaxis=dict(title="绩效系数"),
        showlegend=False
    )
    return fig


def main():
    # 1️⃣ 读取所有月份的绩效数据
    df_all = load_all_monthly_data()
    if df_all.empty:
        print("❌ 没有读取到任何绩效数据，请检查路径或文件格式")
        return

    # 2️⃣ 获取所有员工姓名
    employees = df_all["员工"].unique()
    print(f"✅ 找到 {len(employees)} 位员工的绩效数据")

    # 3️⃣ 确保输出目录存在
    os.makedirs(IMAGE_RESULT_DIR, exist_ok=True)

    # 4️⃣ 逐员工绘制最近12个月柱状图
    for emp in employees:
        fig = plot_employee_bar(df_all, emp)
        save_path = os.path.join(IMAGE_RESULT_DIR, f"{emp}.html")
        fig.write_html(save_path)
        print(f"✅ {emp} 的绩效图已生成：{save_path}")

    print("🎉 所有员工绩效图已生成完成")


if __name__ == "__main__":
    main()
